//
//  YiHttpRequest+Netease.swift
//  yiplayer
//
//  Created by cgw on 2024/5/13.
//

import Foundation

extension YiHttpRequest{
    func neteaseRequest(caller: NSObject, url: String, parameters: [String:String], isPost:Bool = true, complete:@escaping (Any?, NSError?) -> Void) {
        let method = isPost ? BLHttpRequest.Method.POST : BLHttpRequest.Method.GET
        BLHttpRequest.sharedInstance.request(url: url, parameters: parameters, caller: caller, isJsonType: false, method: method) { request in
            request.setValue("http://music.163.com/", forHTTPHeaderField: "referer")
        } complete: { data, err in
            
            DispatchQueue.main.async {
                if data != nil && err == nil {
                    let (d, e) = self.analysisData(data: data)
                    complete(d, e)
                }else {
                    complete(data, err)
                }
            }
        }
    }
    
    //网易歌曲搜索、返回歌曲列表（YiSong列表）
    func neteaseSearch(caller: NSObject, keyword: String, complete:@escaping (Any?, NSError?) -> Void) {
        let count = 10
        let para: [String : Any] =
        [
            "method": "POST",
            "url": "http://music.163.com/api/cloudsearch/pc",
            "params": ["s": keyword, "type": 1, "offset": 0, "limit": count]
        ]
        let ed = NeteaseApi.encodeNeteaseData(para)
//let rightValue = """
//17A079AEEC65C2F0ED808E0127508379724A9B3B2DF476B7659C2A01B91D28A94ACA2781E12D493F813B3A51892C6AE15DCB64389B95047980EDD6F98E59BD5719913094A266AD5AF6646D7750068AC15C98863DAADD14E7CC5B8FADACCE618CE37CFB69885201900791A5D9D03D6B5BB010751ACAD0B4F7300B8AAB8602EE4EF0E97D78067B9DDCD5EAE17CC69B19ADE7994A4D6737ACF44E683DDFC5023AA1
//"""
        let data = ["eparams": ed]
        
        let ul = "http://music.163.com/api/linux/forward"
        self.neteaseRequest(caller: caller, url: ul, parameters: data) { data, err in
            print("end netease")
            
            let redic = (data as? [String: Any])?["result"]
            
            let d = self.datasWithDic(dic: redic, dataKey: "songs", modelName: "YiSong", dicToModelSelector: "neteaseSong:")
            complete(d, err)
        }
    }
    
    //获取网易云音乐的Mp3的链接
    func neteaseMp3Url(caller: NSObject, songId: String?, complete:@escaping (Any?, NSError?) -> Void) {
        
        let para: [String : Any] =
        [
            "ids": [Int(songId ?? "0") ?? 0],
            "br": 32000,
        ]
        let pa = NeteaseApi.encryptedRequest(para: para)
        
        /* 测试参数
        let pa1 = ["params":"bkpUkdGDonNWDqSlNFG6p9PHlY/cpM+h59j6TRThzPzbLYA+WcFAE7mQqo7Qg+Zn7GV/GOSNQe0gpmeo0JUCk3fgGa1RbVmGILlQsopyKfo=",
                   "encSecKey":"620a239ddf18f59476c7a30e67be70566dfe19900a7d79085b6eb4dd3c961b735957074ff035a0282cbada03ec798d7d437289e8124f2a1de9efa1905e5fb813df3b154d7c7c76f6bc91e72017a8617abb831ed72a54e00c6086252ee9506106e2a52006760094327f6987aafde04f1c9a192eaa2a6af45e8315dde7d472d419"]
        */
        let ul = "http://music.163.com/weapi/song/enhance/player/url"
        self.neteaseRequest(caller: caller, url: ul, parameters: pa) { data, err in
            
            print("end mp3 url request")
//            if let dic = data as? [String: [[String:Any]]] {
            if let arr = (data as? [String:Any])?["data"] as? [[String:Any]] {
                if arr.count > 0 {
                    let dd = arr[0]
                    let mp3url = String.formatObject(obj: dd["url"]) ?? ""
                    let br = Int.formatObject(dd["br"]) ?? -1
                    let size = Int.formatObject(dd["size"]) ?? -1
                    //mp3链接、歌曲质量、大小
                    complete((mp3url,br,size), err)
                    return
                }
            }
            
            let er = BLError.error(msg: "获取数据失败")
            complete(nil, er)
        }
    }
    
    func downloadNeteaseLyric(caller: NSObject, songId: String?, complete:@escaping (Any?, NSError?) -> Void) {
        let row_data = ["csrf_token": "", "id": Int(songId ?? "0") ?? 0, "lv": -1, "tv": -1] as [String : Any]
        let pa = NeteaseApi.encryptedRequest(para: row_data)
        let url = "https://music.163.com/weapi/song/lyric"
        self.neteaseRequest(caller: caller, url: url, parameters: pa) { data, err in
            print("end lyric url request")
        
            // 返回的歌词是纯字符串
            if let dic = data as? [String: Any] {
                let ddic = dic["lrc"] as? [String: Any]
                if let lyricStr = ddic?["lyric"] {
                    complete(lyricStr, err)
                    return
                }
            }
            
            let er = BLError.error(msg: "获取数据失败")
            complete(nil, er)
        }
    }
    
    /// 下载网易歌曲
    func downloadNeteaseMp3(song: YiSong, progress:@escaping (((Float)->Void)), complete:@escaping (Any?, NSError?) -> Void) {
        if song.song_url.count < 5 {
            comError(msg: "下载失败, url不正确", complete: complete)
            return
        }
        
        let dir = YiFilePath.share.songDir
        if dir.count < 10 {
            comError(msg: "下载失败, 存放路径错误", complete: complete)
            return
        }
        
        if (song.name?.count ?? 0) < 3 {
            comError(msg: "下载失败, 歌曲名称错误", complete: complete)
            return
        }
        
        let filename = song.name!
        let fullpath = dir.appendPath(pathname: filename)
        if FileManager.default.fileExists(atPath: fullpath) {
            comError(msg: "歌曲已存在", complete: complete)
            return
        }
        
        self.download(url: song.song_url, toDir: dir, fileName: filename) { pro in
            progress(pro)
        } complete: { filePath, err in
            complete(filePath, err)
        }
    }
}
